package controllers;

import java.util.List;

import models.Customer;

import models.Orders;
import models.Product;
import org.springframework.beans.factory.annotation.Autowired;

import play.mvc.Controller;
import play.data.Form;
import play.mvc.Result;
import services.CustomerService;
import services.OrderService;
import services.ProductService;
import views.html.*;

@org.springframework.stereotype.Controller
public class Application extends Controller {
  
	@Autowired
	private CustomerService customerService;
    @Autowired
    private OrderService ordersService;
    @Autowired
    private ProductService productService;
	private String valueSearch;

    public Result index() {
    	valueSearch = "";
    	List<Customer> cusList = customerService.getAllCustomers();
    	return ok(index.render("List of Customers", cusList, valueSearch));
    }
    
    public Result searchCustomers() {
    	Form<String> searchForm = Form.form(String.class).bindFromRequest();
    	valueSearch = searchForm.field("filter").value();
    	return redirectUtil(valueSearch);
	}

    public Result createCustomer() {
    	Form<Customer> f = new Form<Customer>(Customer.class);
		return ok(add.render("Create Customer", f));
	}
    
    public Result addCustomer() {
    	Form<Customer> f = Form.form(Customer.class).bindFromRequest();
    	if(f.hasErrors()){
			return badRequest(add.render("List of Customer", f));
		} else {
			Customer cus = f.get();
			customerService.insertCustomer(cus);
			return redirectUtil(valueSearch);
		}
	}
	public Result delCustomer(int id) {
		customerService.deleteCustomer(id);
		return redirectUtil(valueSearch);
	}
	
	public Result editCustomer(int id) {
		Form<Customer> f = new Form<Customer>(Customer.class);
		Customer cus = customerService.getCustomerById(new Integer(id));
		Form<Customer> fNew= f.fill(cus);
		return ok(form.render("Edit Customer", fNew));
	}
	
	public Result updateCustomer(){
		Form<Customer> f = Form.form(Customer.class).bindFromRequest();
    	if(f.hasErrors()){
			return badRequest(form.render("Update fail", f));
		} else {
			Customer cus = f.get();
			customerService.updateCustomer(cus);
			return redirectUtil(valueSearch);
		}
	}

	private Result redirectUtil(String filter){
		if (!filter.equals(null) && !filter.equals("")){
			List<Customer> cusList = customerService.getCustomersLikeName("%" + filter.trim() + "%");
    		return ok(index.render("List of Customers", cusList, filter));
    	}
    	return redirect(routes.Application.index());
	}



	
	public String getValueSearch() {
		return valueSearch;
	}
	public void setValueSearch(String valueSearch) {
		this.valueSearch = valueSearch;
	}
		
}


